package com.atguigu.srb.sms.controller.api;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/api/sms")
@Api(tags = "短信管理")
@Slf4j
@RequiredArgsConstructor
public class ApiSmsController {

    private final SmsService smsService;

    private final RedisTemplate<String, Object> redisTemplate;

    private final CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping(value = "/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable String mobile) {

        // 手机号是否注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        System.out.println("result = " + result);
        Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);

        // MOBILE_NULL_ERROR(-202, "手机号码不能为空"),
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);

        // MOBILE_ERROR(-203, "手机号码不正确"),
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        // 生成验证码
        String code = RandomUtils.getFourBitRandom();

        // 组装短信模板参数
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        // 发送短信
        // smsService.send(mobile, SmsProperties.TEMPLATE_CODE, param);

        // 将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功:" + code);
    }

}
